//
//  WordDicTableViewController.m
//  万词王
//
//  Created by rimi on 2016/11/30.
//  Copyright © 2016年 dongfumei. All rights reserved.
//

#import "WordDicTableViewController.h"
#import "WordDicTableViewCell.h"

@interface WordDicTableViewController () <UITextFieldDelegate>{
    id _oberver;
}

@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, strong) UITextField *searchField;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger rows;

@end

@implementation WordDicTableViewController

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:_oberver];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _oberver = [[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidChangeNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        [self initializeDataSource:self.searchField.text];
    }];
    
    self.tableView.tableHeaderView = self.searchField;
    [self.tableView registerNib:[UINib nibWithNibName:@"WordDicTableViewCell" bundle:nil] forCellReuseIdentifier:@"WordDicTableViewCell"];
    
    self.tableView.estimatedRowHeight = 60;
    //
    self.tableView.rowHeight = UITableViewAutomaticDimension;
}


-(void)initializeDataSource:(NSString *)string {
    NSString *url=@"http://api.avatardata.cn/CiHai/Query";
    NSLog(@"%@", self.searchField.text);
    NSDictionary *dic=@{@"key":@"8a2b87ac4d6c4d9898144fc0aa882a58",@"keyWord":string,@"page":@"1"};
    
    AFHTTPSessionManager   *manager=[AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/javascript", nil];
    
    [manager GET:url parameters:dic progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        
        if ([responseObject[@"reason"] isEqualToString:@"Succes"]) {
            self.dataSource=[responseObject[@"result"] mutableCopy];
            
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error.localizedDescription);
        
    }];

}

#pragma mark - UITextFieldDelegater
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    return YES;
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    return YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.searchField resignFirstResponder];
    return YES;
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WordDicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WordDicTableViewCell" forIndexPath:indexPath];
    
    cell.nameLabel.text = _dataSource[indexPath.row][@"words"];
    cell.detailLabel.text = _dataSource[indexPath.row][@"content"];
    
    return cell;
}



-(UITextField *)searchField{
    if (!_searchField) {
        _searchField = [[UITextField alloc]initWithFrame:AAdaptionRect(20, 10, kBaseWidth/AAdaptationWidth() - 40, 50)];
        _searchField.backgroundColor = MainColor;
        _searchField.placeholder = @"🔍请输入你要查找的字";
        _searchField.layer.cornerRadius = 10;
        _searchField.layer.masksToBounds = YES;
        _searchField.delegate = self;
        [_searchField canBecomeFirstResponder];
        _searchField.font=[UIFont systemFontOfSize:15];
        _searchField.autocapitalizationType=UITextAutocapitalizationTypeNone;;
        _searchField.clearButtonMode=UITextFieldViewModeWhileEditing;
        _searchField.returnKeyType=UIReturnKeySearch;
    }
    return _searchField;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
